package com.example.module_park.adapter


import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.module_park.R

class AttachmentAdapter(
    var items: List<String>,
    private val onAddClick: () -> Unit,
    private val onRemoveClick: (String) -> Unit
) : RecyclerView.Adapter<AttachmentAdapter.AttachmentViewHolder>() {

    companion object {
        private const val TYPE_ADD = 0
        private const val TYPE_ITEM = 1
        private const val MAX_ATTACHMENTS = 9
    }

    override fun getItemViewType(position: Int): Int {
        return when {
            position < items.size -> TYPE_ITEM
            else -> TYPE_ADD
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AttachmentViewHolder {
        return when (viewType) {
            TYPE_ADD -> AddViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_attachment_add, parent, false)
            )
            else -> AttachmentItemViewHolder(
                LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_attachment, parent, false)
            )
        }
    }

    override fun onBindViewHolder(holder: AttachmentViewHolder, position: Int) {
        when (holder) {
            is AddViewHolder -> holder.bind(onAddClick)
            is AttachmentItemViewHolder -> holder.bind(items[position], onRemoveClick)
        }
    }

    override fun getItemCount(): Int {
        return items.size + if (items.size < MAX_ATTACHMENTS) 1 else 0
    }

    sealed class AttachmentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    class AddViewHolder(itemView: View) : AttachmentViewHolder(itemView) {
//        private val btnAdd: Button = itemView.findViewById(R.id.btnAddAttachment)

        fun bind(onClick: () -> Unit) {
//            btnAdd.setOnClickListener { onClick() }
        }
    }

    class AttachmentItemViewHolder(itemView: View) : AttachmentViewHolder(itemView) {
        private val ivImage: ImageView = itemView.findViewById(R.id.ivAttachment)
        private val btnRemove: ImageButton = itemView.findViewById(R.id.btnRemoveAttachment)

        fun bind(url: String, onRemove: (String) -> Unit) {
            // 使用Glide加载图片
            Glide.with(ivImage.context)
                .load(url)
                .placeholder(R.drawable.placeholder)
                .into(ivImage)

            btnRemove.setOnClickListener { onRemove(url) }
        }
    }
}